package com.lindroy.androidplayer.ui.adapter

import androidx.lifecycle.LifecycleOwner
import com.lindroy.androidplayer.base.adapter.BaseListAdapter
import com.lindroy.androidplayer.databinding.SearchHistoryItemBinding
import com.lindroy.androidplayer.interfaces.OnItemChildClickListener
import com.lindroy.androidplayer.viewmodels.SearchHistoryItemViewModel
import com.lindroy.androidplayer.viewmodels.SearchHotKeyViewModel

/**
 * @author Lin
 * @date 2022/3/10
 * @function
 */
class SearchHistoryAdapter(owner: LifecycleOwner) :
    BaseListAdapter<SearchHistoryItemViewModel, SearchHistoryItemBinding>(owner) {

    private var removedListener: ((String) -> Unit)? = null

    init {
        setOnChildLongClickListener { view, item, position ->
            itemList.forEach { it.isRemoveEnable.postValue(true) }
            true
        }
    }

    fun setNewData(list: List<String>) {
        setData(list.map { SearchHistoryItemViewModel(it) })
    }

    fun setOnRemoveItemListener(listener: (String) -> Unit) {
        removedListener = listener
    }

    override fun SearchHistoryItemBinding.onBindViewHolder(
        item: SearchHistoryItemViewModel,
        position: Int
    ) {
        vm = item
        chipKeyword.setOnCloseIconClickListener {
            removedListener?.invoke(item.keyword)
        }
    }

    override fun SearchHistoryItemBinding.onBindChildClick(itemClickListener: OnItemChildClickListener<SearchHistoryItemViewModel>) {
        itemClick = itemClickListener
    }

    override fun artItemsTheSame(
        oldItem: SearchHistoryItemViewModel,
        newItem: SearchHistoryItemViewModel
    ) = oldItem.keyword == newItem.keyword

    override fun areContentsTheSame(
        oldItem: SearchHistoryItemViewModel,
        newItem: SearchHistoryItemViewModel
    ) = oldItem.keyword == newItem.keyword


}